package Model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.sun.rowset.CachedRowSetImpl;

import Database.*;
import Helper.*;

public class AdminM extends Model {
    ArrayList<Admin> cache = null;

    public Admin login(String name, String password) {
        AdminM adminM = new AdminM();
        ArrayList<Admin> temp = adminM.find(name);

        Admin result = null;

        if (temp.size() == 1) {
            Admin a = temp.get(0);

            if (a.name.equals(name) && a.getPassword().equals(Helper.md5(password))) {
                a.setStatus(name, Helper.md5(password));

                result = a;
            } else {
                System.err.println("用户名或密码错误！");
            }
        } else {
            System.err.println("用户名不存在！");
        }

        return result;
    }

    private ArrayList<Admin> find(String name){
        AdminDB db = new AdminDB();

        CachedRowSetImpl res = db.match(name);

        return createadminArr(res);
    }

    private ArrayList<Admin> createadminArr(CachedRowSetImpl res){
        // override

        ArrayList<Admin> result = new ArrayList<>();

        try {
            while (res.next()) {
                Admin a = new Admin(res.getString(3),res.getString(4));
                a.id = res.getInt(1);

                result.add(a);
            }
        } catch (SQLException exception) {
            System.err.println("数据库出错！");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }

        return result;
    }
}

class AdminDB extends DB {
    CachedRowSetImpl match(String name){
        CachedRowSetImpl cachedRowSet = null;

        try{
            connect();

            String sql = "SELECT * FROM tb_account WHERE name=? AND auth=2";
            PreparedStatement statement = dbConnection.prepareStatement(sql);
            statement.setString(1, name);

            ResultSet res = statement.executeQuery();

            cachedRowSet = new CachedRowSetImpl();
            cachedRowSet.populate(res);
        }catch(SQLException exception){
            System.err.println("数据库出错！");
            if( Helper.isDev ){
                exception.printStackTrace();
            }
        }finally {
            close();
        }

        return cachedRowSet;
    }
}
